package cn.kgc.controller.logic.document;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import cn.kgc.pojo.Document;
import cn.kgc.pojo.User;
import cn.kgc.service.document.gth_documentServer;
import cn.kgc.utils.QiniuUtils;
import cn.kgc.utils.TestQiniuConfig;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@Controller
@RequestMapping("/document")
public class Gth_document {

    @Resource
    private gth_documentServer server;


    //查询全部跳转到gth-cate
    @RequestMapping("/listdocument")
    public ModelAndView listdocument(Integer currentPage, Integer pageSize, String title, Integer type, String createDate, Integer id, Model model, HttpServletRequest request){
        if (currentPage == null || pageSize == null){
            currentPage = 1;
            pageSize = 5;
        }
        System.out.println("currentPage-----------------------------:"+currentPage);


        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");

        ModelAndView mv = new ModelAndView();

        PageHelper.startPage(currentPage,pageSize);
        Page<Document> selall = server.selall(title,type,createDate,id,user.getId());

        for (Document s:selall) {
            System.out.println(s);
        }
        PageInfo pageInfo = new PageInfo(selall);
        System.out.println("pageinfo$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"+pageInfo);
        mv.addObject("selall",pageInfo);
        mv.setViewName("document/gth-cate");
        return mv;
    }

    //查询全部跳转到gth-orderlist
    @RequestMapping("/orderlist")
    public String orderlist(String title, Integer type, String createDate,Integer id,Integer u_id,HttpServletRequest request,Model model){
        title = null;
        type = null;
        createDate = null;
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        u_id = user.getId();
        List<Document> order = server.selall(title,type,createDate,id,u_id);
        for (Document s:order) {
            System.out.println(s);
        }
        model.addAttribute("order",order);
        return "document/gth-order-list";
    }

    //通过查询条件，显示数据
    @GetMapping("/orderinfo")
    @ResponseBody
    public String orderinfo(Integer currentPage, Integer pageSize,String title, Integer type, String createDate,Integer id, Integer u_id,HttpServletRequest request,Model model){
        System.out.println("这是ctroller层打印的title"+title);
        System.out.println("这是ctroller层打印的type"+type);
        id=null;
        if (currentPage == null || pageSize == null){
            currentPage = 1;
            pageSize = 5;
        }
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        u_id = user.getId();

        PageHelper.startPage(currentPage,pageSize);
        Page<Document> info = server.selall(title,type,createDate,id,u_id);
        for (Document s: info) {
            System.out.println("这是ctroller层打印的输出语句----------------------------"+s);
        }
        PageInfo pageInfo = new PageInfo(info);
        return JSON.toJSONString(pageInfo);
    }

    @RequestMapping("/orderby")
    public String orderby(@Param("id") Integer id,@Param("title") String title,Model model,Integer u_id,HttpServletRequest request){
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        u_id = user.getId();
        List<Document> selbyid = server.selbyid(id,title,u_id);
        for (Document s: selbyid) {
            System.out.println("这是orderby ctroller层打印的输出语句----------------------------"+s);
        }
        model.addAttribute("orderby",selbyid);
        return "document/gth-order-list";
    }

    @RequestMapping("/orderby2")
    @ResponseBody
    public String orderby2(@Param("id") Integer id,@Param("title") String title,@Param("u_id")Integer u_id,HttpServletRequest request){
        System.out.println("这是orderby2 ctroller层打印的title"+title);
        System.out.println("这是orderby2 ctroller层打印的type"+id);
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        u_id = user.getId();
        List<Document> selbyid = server.selbyid(id,title,u_id);
        for (Document s: selbyid) {
            System.out.println("这是orderby2 ctroller层打印的输出语句----------------------------"+s);
        }
        return JSON.toJSONString(selbyid);
    }

    @RequestMapping("/sellrecycler")
    public ModelAndView sellrecycler(Integer currentPage, Integer pageSize,Integer u_id,HttpServletRequest request){
        if (currentPage == null || pageSize == null){
            currentPage = 1;
            pageSize = 5;
        }
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        u_id = user.getId();
        ModelAndView mv = new ModelAndView();

        PageHelper.startPage(currentPage,pageSize);

        Page<Document> selrecall = server.selrecall(u_id);

        for (Document s: selrecall) {
            System.out.println("这sellrecycler ctroller层打印的输出语句----------------------------"+s);
        }
        PageInfo pageInfo = new PageInfo(selrecall);
        mv.addObject("selrecall",pageInfo);
        mv.setViewName("document/gth-recycler");
        return mv;
    }

    @RequestMapping("/lookbyid")
    @ResponseBody
    public String lookbyid(Integer id,HttpServletRequest request,Integer u_id){
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        u_id = user.getId();
        Document lookbyid = server.lookbyid(id,u_id);
        return JSON.toJSONString(lookbyid);
    }

    @RequestMapping("/updatebyid")
    @ResponseBody
    public Integer updatebyid(@Param("id")Integer id,@Param("title")String title){
        int coupdate = server.coupdate(id, title);
        return coupdate;
    }

    @RequestMapping("/reupdate")
    @ResponseBody
    public Integer reupdate(Integer id){
        int reupdate = server.reupdate(id);
        return reupdate;
    }


    @RequestMapping("/cateupdate")
    @ResponseBody
    public Integer cateupdate(Integer id){
        int cateupdate = server.cateupdate(id);
        return cateupdate;
    }

    @RequestMapping("/redel")
    @ResponseBody
    public Integer redel(Integer id){
        int redel = server.redel(id);
        return redel;
    }

    @RequestMapping("/addfile")
    @ResponseBody
    public Integer addfile(@Param("title")String title,@Param("dp_id")Integer dp_id,@Param("path")String path,@Param("parentId")Integer parentId,Integer u_id,HttpServletRequest request){
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        u_id = user.getId();
        int addfile = server.addfile(title, dp_id, path, parentId,u_id);
        return addfile;
    }

    @RequestMapping("/repeatName")
    @ResponseBody
    public Boolean repeatName(@Param("title")String title){
        Boolean name = server.repeatName(title);
        return name;
    }

    @RequestMapping("/tofiles")
    public String tofiles(@Param("id")Integer id,Model model,@Param("u_id") Integer u_id,HttpServletRequest request){
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        u_id = user.getId();
        Document lookbyid = server.lookbyid(id,u_id);
        model.addAttribute("fil",lookbyid);
        return "document/gth-files";
    }

    /**
     * 处理上传文件：保存文件信息到数据库
     * 注意参数MultipartFile的变量名必须和表单中的name属性一致，这样才可以接收到文件
     */
    @PostMapping("/upload1")
    public String upload(MultipartFile aaa,HttpServletRequest request,Document document) throws IOException {
        // 获取原文件名
        String oldFilename = aaa.getOriginalFilename();

        // 获取原文件的后缀名
        String extension = "." + FilenameUtils.getExtension(oldFilename);

        // 生成新文件名
        String newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + extension;

        // 文件大小
        long size = aaa.getSize();

        // 文件类型
        int type = 0;
        if (extension.equals(".doc")){
            type = 2;
        }else  if (extension.equals(".txt")){
            type = 3;
        }else if (extension.equals(".jpg")){
            type = 4;
        }else if (extension.equals(".pdf")){
            type = 5;
        }else if (extension.equals(".xls")){
            type = 6;
        }else  if (extension.equals(".zip")){
            type = 7;
        }

        // 以下属性放到业务层Service去做
        // 图片ID
        // 是否是图片
        // 下载次数
        // 上传时间

        // 根据日期生成目录
        String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/files";
        String dateFormat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dateDirPath = realPath + "/" + dateFormat;

        File dateDir = new File(dateDirPath);
        if (!dateDir.exists()) {
            dateDir.mkdirs();    // mkdirs()可以创建多级目录
        }

        // 处理上传文件
        aaa.transferTo(new File(dateDirPath, newFileName));

        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        // 将文件信息放入数据库中保存
        // 注意，我们现在在控制层，某一些业务需要放到业务层去做
        Document userFile = new Document();
        userFile.setTitle(oldFilename);
        userFile.setNewfilename(newFileName);
        userFile.setType(type);
        userFile.setU_id(user.getId());
        userFile.setDp_id(document.getDp_id());
        userFile.setPath("/files/" + dateFormat);
        userFile.setParentId(document.getParentId());
        //调用保存方法
        server.save(userFile);
        return "gth-jump";
    }

    @RequestMapping("/upload")
    @ResponseBody
    public String upload1(@RequestParam("aaa")MultipartFile aaa, HttpServletRequest request, HttpServletResponse response,Document document) throws IOException {
        // 获取原文件名
        String oldFilename = aaa.getOriginalFilename();
        // 获取原文件的后缀名
        String extension = "." + FilenameUtils.getExtension(oldFilename);
        // 用来获取其他参数
        MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);

        //String name = params.getParameter("username");
        if (!aaa.isEmpty()) {
            FileInputStream inputStream = (FileInputStream) aaa.getInputStream();
            // 生成新文件名
            String newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+ extension;

            //获取文件类型
            String contentType = aaa.getContentType();
            int type = 0;
            if (extension.equals(".doc")){
                type = 2;
            }else  if (extension.equals(".txt")){
                type = 3;
            }else if (extension.equals(".jpg")){
                type = 4;
            }else if (extension.equals(".pdf")){
                type = 5;
            }else if (extension.equals(".xls")){
                type = 6;
            }else  if (extension.equals(".zip")){
                type = 7;
            }
            System.out.println("文件类型-----------------------"+type);
            HttpSession session = request.getSession();
            User user = (User)session.getAttribute("user");
            //前缀
            boolean isPre = contentType.startsWith("image");
            System.out.println("是否是图片：" + isPre);
            String path = QiniuUtils.uploadQNFile(inputStream, newFileName);

            System.out.println("图片大小（字节）：" + aaa.getSize());

            System.out.println("七牛云返回的图片链接:" + path);
            Document userFile = new Document();
            userFile.setTitle(oldFilename);
            userFile.setNewfilename(newFileName);
            userFile.setType(type);
            userFile.setU_id(user.getId());
            userFile.setDp_id(document.getDp_id());
            userFile.setPath(path);
            userFile.setParentId(document.getParentId());
            System.out.println("document的id==============================================="+document.getId());
            System.out.println("upload的中传的实体类------------------------"+document);
            int save = server.save(userFile);
            
            return "<script>alert('文件上传成功！');location.href='/document/tofiles?id="+document.getId()+"';</script>";
        }
        return "<script>alert('文件上传失败！');location.href='/document/tofiles?id="+document.getId()+"';</script>";


    }


    /**
     * 文件下载
     */
    @RequestMapping("/download1")
    public void download(String openStyle, Integer id, HttpServletResponse response,HttpServletRequest request) throws IOException {
        openStyle = openStyle == null ? "attachment" : openStyle;
        // 根据文件id获取对应的文件信息
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        Document userFile = server.lookall(id, user.getId());

        // 获取文件路径
        System.out.println("File: ===========================================" + userFile);
        // 获取文件输入流（把磁盘上的文件通过IO加载到程序（内存）中
        FileInputStream fis = new FileInputStream(new File("http:././"+userFile.getPath()));
        // 附件下载
        // 注意：为防止中文乱码，需要使用UTF-8
        response.setHeader("content-disposition", openStyle + ";fileName=" + URLEncoder.encode(userFile.getTitle(), "UTF-8"));
        // 获取响应流（找到后需要通过Response发送回给用户
        ServletOutputStream os = response.getOutputStream();
        // 文件拷贝
        IOUtils.copy(fis, os);
        // 关闭流
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(os);
    }




    @RequestMapping("/download")
    public String download1(String title) throws IOException {
        download(title);
        return "document/gth-jump";
    }


//    /**
//     * 下载全部
//     */
//    public static void list() {
//        //构造一个带指定Zone对象的配置类
//        Configuration cfg = new Configuration(Region.region0());
//        //...其他参数参考类注释
//        Auth auth = Auth.create(TestQiniuConfig.AK, TestQiniuConfig.SK);
//        BucketManager bucketManager = new BucketManager(auth, cfg);
//
//        //文件名前缀
//        String prefix = "";
//        //每次迭代的长度限制，最大1000，推荐值 1000
//        int limit = 10;
//        //指定目录分隔符，列出所有公共前缀（模拟列出目录效果）。缺省值为空字符串
//        String delimiter = "";
//
//        //列举空间文件列表
//        BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(TestQiniuConfig.BUCKET, prefix, limit, delimiter);
//        while (fileListIterator.hasNext()) {
//            //处理获取的file list结果
//            FileInfo[] items = fileListIterator.next();
//            for (FileInfo item : items) {
//                System.out.println("************************=" + item.key);
//                download(item.key);//下载
//            }
//        }
//    }



    /**
     * 下载
     */
    public static void download(String fileName) throws IOException {
        String domainOfBucket = "r7uh8k7h0.hb-bkt.clouddn.com";
        String encodedFileName = null;
        try {
            encodedFileName = URLEncoder.encode(fileName, "utf-8").replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);

        Auth auth = Auth.create(TestQiniuConfig.AK, TestQiniuConfig.SK);
        long expireInSeconds = 3600;//1小时，可以自定义链接过期时间
        String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
        System.out.println(finalUrl);
        File dateDir = new File("D://七牛云2");
        if (!dateDir.exists()) {
            dateDir.mkdirs();    // mkdirs()可以创建多级目录
        }
        HttpUtil.downloadFile(finalUrl, FileUtil.file("d://七牛云2"));

    }

}
